import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'

import MainLayout from '@/layouts/MainLayout.vue'
import { ElMessage } from 'element-plus'
import { getUserDetailAPI } from '@/apis/user'
import { useUserStore } from '@/stores/user'
import { useUserDetailStore } from '@/stores/userDetail'
import { asyncFeaturesRoutes, asyncRoutes } from './asyncRoutes'
import { useMenuStore } from '@/stores/menu'

// 路由表
export const routes: RouteRecordRaw[] = [
  // 登录页
  {
    path: '/login',
    component: () => import('@/views/login/LoginPage.vue'),
    meta: { hidden: true },
  },
  // 首页
  {
    path: '/',
    redirect: '/workbench',
    meta: { hidden: true },
  },
  // 首页
  {
    path: '/workbench',
    component: MainLayout,
    children: [
      {
        path: '',
        component: () => import('@/views/workbench/WorkbenchPage.vue'),
        meta: { title: '工作台', icon: 'workbench' },
      },
    ],
  },
  // 404
  {
    path: '/:pathMatch(.*)*',
    component: () => import('@/views/NotFound.vue'),
    meta: { hidden: true },
  },
]

// 路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  scrollBehavior: () => ({ top: 0 }),
  routes,
})

/** 重置路由 */
export const resetRouter = () => {
  router.getRoutes().forEach(route => {
    const { meta, name } = route // 获取当前路由名称
    if (name && router.hasRoute(name)) { // 判断路由是否存在且有名称
      if (meta.permission) { // 判断路由是否有菜单权限
        router.removeRoute(name) // 删除路由
      }
      if (meta.permissionFeatures) { // 判断路由是否有功能权限
        router.removeRoute(name) // 删除路由
      }
    }
  })
}

const whiteList = ["/login", "/404"] // 白名单

// "sys:user:list" 一级:二级:功能
// 处理一级路由数据
const getFirstRoutePerms = (permsArr: string[]) => {
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}
// 处理二级路由权限数据
const getSecondRoutePerms = (permsArr: string[]) => {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}
// 筛选菜单权限路由
const getRoutes = (
  getFirstRoutePerms: string[], // 一级路由权限
  getSecondRoutePerms: string[], // 二级路由权限
  asyncRoutes: RouteRecordRaw[] // 异步路由
) => {
  // 超级管理员 *:*:*
  if (getFirstRoutePerms.includes('*')) {
    return [...asyncRoutes]
  }

  // 筛选一级路由
  const firstRoutes = asyncRoutes.filter(route => getFirstRoutePerms.includes(route.meta?.permission!))
  // 筛选 ---- 整个路由
  const lastRoutes = firstRoutes.map(route => {
    return {
      ...route,
      // 筛选 ---- 二级路由
      children: route.children?.filter(son => getSecondRoutePerms.includes(son.meta?.permission!))
    }
  })
  return lastRoutes
}

// 筛选功能权限路由
const getFeaturesRoutes = (permissionFeatures: string[]) => {
  // 超级管理员 *:*:*
  if (permissionFeatures.includes('*:*:*')) {
    return asyncFeaturesRoutes
  }
  // 筛选功能权限路由
  return asyncFeaturesRoutes.filter(route => {
    return permissionFeatures.includes(route.meta?.permissionFeatures as string)
  })
}

// 路由前置守卫
router.beforeEach(async (to, from, next) => {
  // 获取pinia user模块
  const userStore = useUserStore()
  // 是否登录
  if (userStore.token) {
    // 获取设置用户信息
    const userDetailStore = useUserDetailStore() // user详情仓库
    if(!userDetailStore.userDetail.id){
      const res = await getUserDetailAPI() // 获取用户信息

      userDetailStore.setUserDetail(res.data) // 存储用户信息
      console.log(res.data)

      // 获取菜单一级路由
      const firstRoutePerms = getFirstRoutePerms(res.data.permissions)
      // 获取菜单二级路由
      const secondRoutePerms = getSecondRoutePerms(res.data.permissions)
      // 获取菜单权限路由
      const newAsyncRoutes = getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes)
      // 动态添加每一个菜单权限路由
      newAsyncRoutes.forEach(route => {
        router.addRoute(route as RouteRecordRaw)
      })

      // 获取功能权限路由
      const newFeatureRoutes = getFeaturesRoutes(res.data.permissions)
      // 动态添加每一个功能权限路由
      newFeatureRoutes.forEach(route => {
        router.addRoute(route as RouteRecordRaw)
      })
      
      // 存储权限路由列表
      const menuStore = useMenuStore()
      menuStore.setMenuList([...newAsyncRoutes as RouteRecordRaw[], ...newFeatureRoutes as RouteRecordRaw[]])

      // 动态添加路由addRoute的固定放行写法，不知道为什么
      next({...to})
    } else {
      // 放行
      next()
    }

  } else {
    // 是否在白名单中
    if (whiteList.includes(to.path)) {
      // 放行
      next()
    } else {
      // 不在白名单中，跳转到登录页
      next('/login')
      ElMessage.warning('你都某登录，请先登录')
    }
  }
})

export default router
